package com.hrzyit.whistle.comm.ui.activity

import android.os.Bundle
import android.support.v4.app.Fragment
import com.alibaba.android.arouter.facade.annotation.Route
import com.hrzyit.base.ui.activity.BaseActivity
import com.hrzyit.provider.routers.RouterPath
import com.hrzyit.whistle.comm.R
import com.hrzyit.whistle.comm.common.CommConstant
import com.hrzyit.whistle.comm.ui.fragment.ContactsFragment
import com.hrzyit.whistle.comm.ui.fragment.DepartmentFragment
import com.hrzyit.whistle.comm.ui.fragment.UserInfoFragment
import java.util.*

/**
 * 通讯录界面容器，其中包含有单位列表和人员列表 Fragment
 * @author YangWei
 * @date 2019/4/19
 */
@Route(path = RouterPath.CommunicationCenter.PATH_COMM_MAIN)
class ContactMainActivity : BaseActivity() {
    companion object {
        const val TAG = "ContactMainActivity"
    }

    // Fragment 栈
    private var mStack: Stack<Fragment> = Stack()

    // 单位 Fragment
    private val departmentFragment: DepartmentFragment by lazy {
        DepartmentFragment()
    }
    // 人员 Fragment
    private val contactsFragment: ContactsFragment by lazy {
        ContactsFragment()
    }
    // 个人信息 Fragment
    private val userInfoFragment: UserInfoFragment by lazy {
        UserInfoFragment()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_concat_main)

        // 获取 Activity 跳转的附带的参数 fragment_key
        val fragmentKey = intent.getIntExtra("fragment_key", CommConstant.RESULT_CODE_CONTACT_DEPT)

        initFragment()
        // 根据 fragment_key 显示对应 Fragment
        changeFragmentByTag(fragmentKey.toString())
    }


    /**
     * 初始化 Fragment 栈管理
     */
    private fun initFragment() {
        val manager = supportFragmentManager.beginTransaction()
        // 单位信息列表
        manager.add(
            R.id.mConcatMainContainer, departmentFragment, CommConstant.RESULT_CODE_CONTACT_DEPT.toString()
        )
        // 单位联系人信息列表
        manager.add(
            R.id.mConcatMainContainer, contactsFragment, CommConstant.RESULT_CODE_CONTACT_CONTACTS.toString()
        )
        // 联系人详情
        manager.add(
            R.id.mConcatMainContainer, userInfoFragment, CommConstant.RESULT_CODE_CONTACT_DETAIL.toString()
        )
        manager.commit()

        mStack.add(departmentFragment)
        mStack.add(contactsFragment)
        mStack.add(userInfoFragment)
    }

    /**
     * 通过 Tag 切换 Fragment
     */
    private fun changeFragmentByTag(tag: String) {
        val manager = supportFragmentManager.beginTransaction()
        mStack.forEach {
            when (it.tag) {
                tag -> {
                    manager.show(it)
                }
                else -> {
                    manager.hide(it)
                }
            }
        }
        manager.commit()
    }
}
